<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="就诊日期" prop="date">
        <el-date-picker
          v-model="queryParams.date"
          value-format="YYYY-MM-DD"
          type="date"
          placeholder="日期"
          class="!w-120px"
        />
      </el-form-item>
      <el-form-item label="时段" prop="period">
            <el-select
              v-model="queryParams.period"
              placeholder="选择时段"
              clearable
              class="!w-100px"
            >
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.MEDICAL_REGISTER_PERIOD)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
      </el-form-item>
      <el-form-item label="挂号状态" prop="registerStatus">
            <el-select
              v-model="queryParams.registerStatus"
              placeholder="选择挂号状态"
              clearable
              class="!w-160px"
            >
              <el-option
                v-for="dict in filteredPeriodOptions"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list">
      <el-table-column label="编号" align="center" prop="id" />
      <el-table-column label="医师名称" align="center" prop="doctorName" />
      <el-table-column label="病人名称" align="center" prop="patientsName" />
      <el-table-column label="就诊日期" align="center" prop="date" :formatter="dateFormatter2"/>
      <el-table-column label="时段" align="center" key="period">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MEDICAL_REGISTER_PERIOD" :value="scope.row.period" />
        </template>
      </el-table-column>
      <el-table-column label="就诊时间" align="center" prop="consultingTime" :formatter="timeArrayTableFormatter"/>
      <el-table-column label="病人描述" align="center" prop="description" />
      <el-table-column label="病人电话" align="center" prop="mobile" />
      <el-table-column label="挂号状态" key="registerStatus">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.MEDICAL_REGISTER_STATUS" :value="scope.row.registerStatus" />
        </template>
      </el-table-column>
      
      <el-table-column label="操作" align="center">
        <template #default="scope"> 
          <el-button
            link
            type="primary"
            @click="openDescriptionForm(scope.row)"
          >
            修改描述
          </el-button>
          <el-button
            link
            type="primary"
            @click="updateStatus(scope.row.id)"
          >
            确认就诊
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <RecordForm ref="formRef" @success="getList" />
</template>
<script lang="ts" setup>
import RecordForm from './RecordForm.vue';
import { DICT_TYPE, getIntDictOptions, NumberDictDataType } from '@/utils/dict';
import { dateFormatter2, timeArrayTableFormatter } from '@/utils/formatTime';
import * as RegisterApi from '@/api/medical/register';
import * as DoctorApi from '@/api/medical/doctor';
import * as PatientApi from '@/api/medical/patient';
import * as DeptApi from '@/api/system/dept';
import { useMessage } from '@/hooks/web/useMessage';
import { useI18n } from 'vue-i18n';
import { ref, reactive } from 'vue';
import { getUserProfile } from '@/api/system/user/profile'

defineOptions({ name: 'MedicalRecord' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const doctorId = ref() // 医师id
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  doctorId: '',
  patientsId: '',
  deptId: '',
  period: undefined,
  registerStatus: undefined,
  date: ''
})
const queryFormRef = ref() // 搜索的表单
const doctorList = ref([]) // 医生列表
const patientList = ref([]) // 病人列表
const deptList = ref<any[]>([]) // 科类列表 
const filteredPeriodOptions = ref<NumberDictDataType[]>([]);
const allPeriodOptions = getIntDictOptions(DICT_TYPE.MEDICAL_REGISTER_STATUS);

/** 打开修改描述表单 */
const openDescriptionForm = (row: any) => {
  formRef.value.open('description', row.id, { description: row.description })
}

const getUserInfo = async () => {
  const users = await getUserProfile()
  doctorId.value = users.id
}

/** 查询挂号列表 */
const getList = async () => {
  loading.value = true
  try {
    queryParams.doctorId = doctorId.value
    const data = await RegisterApi.getRegisterPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}


/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await RegisterApi.deleteRegister(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/**获取医师列表 */
const getDoctorList = async () => {
  const response = await DoctorApi.getDoctorList()
  console.log('response:', response)
  doctorList.value = response
}

/**获取病人列表 */
const getPatientList = async () => {
  const response = await PatientApi.getPatientList()
  console.log('response:', response)
  patientList.value = response
}

/**获取科类列表 */
const getDeptList = async () => {
  const response = await DeptApi.getSimpleDeptDoctorList()
  console.log('response:', response)
  deptList.value = response
}

/** 更新挂号状态 */
const updateStatus = async (id: number) => {
  try {
    // 这里假设新的状态是已审核，你可以根据实际情况修改
    const newStatus = 3; 
    await message.confirm("确认审核通过？", "状态将更新为已就诊")
    await RegisterApi.updateRegisterStatus(id, newStatus);
    message.success(t('common.updateSuccess'));
    // 刷新列表
    await getList();
  } catch (error) {
    message.error(t('common.updateFailed'));
  }
}

const getDictValue = () => {
filteredPeriodOptions.value = allPeriodOptions.filter(option => option.value >= 2 && option.value <= 4);
}

/** 初始化 **/
onMounted(async () => {
  // 初始化字典数据
  await getDictValue()
  // 初始化数据
  await getUserInfo()
  // 获取列表数据
  await getList()

  await Promise.all([
    getDoctorList(),
    getPatientList(),
    getDeptList()
  ])

})
</script>